import { _decorator, Component, Button,Label, Node, Quat, tween, Vec3, RichText, Color, Sprite, UIOpacity, } from 'cc';
import { Guest } from './Guest'; // 假设 Guest 是乘客的类
import { Upgrade } from './Upgrade'; 
import { ResourceManager } from '../PlayableFramework/Tools/Manager/ResourceManager';
import ads from '../PlayableFramework/Ads/AdsManager';
const { ccclass, property } = _decorator;

@ccclass('QueueManager')
export class QueueManager extends Component {
    @property(Node)
    public entryPoint: Node = null; // 入口位置

    @property(Node)
    public exitPoint: Node = null; // 出口位置

    @property(Node)
    public destination1: Node = null; // 目的地

    @property(Node)
    public destination2: Node = null; // 目的地

    @property(Node)
    public destination3: Node = null; // 目的地

    @property(Node)
    public outPoint: Node = null; // 目的地

    @property(Node)
    public effectUpgrade: Node = null; // 目的地

    @property(Node)
    public queueParent: Node = null; // 存放乘客的父节点

    @property(Button)
    private toggleButton: Button = null; // 按钮

    @property(Button)
    private shopButton: Button = null; // 按钮

    @property(Node)
    public finger: Node = null; // 存放乘客的父节点

    @property(Node)
    public moneyUI: Node = null; // 目的地

    private queue: Guest[] = []; // 当前队列
    private currentPositions: Vec3[] = []; // 当前乘客的位置列表
    private currentRot: Quat[] = []; // 当前乘客的位置列表
    public groupSize: number = 4; // 每组人数
    private interval: number = 0; // 组间间隔时间

    private pay: number = 50; // 组间间隔时间
    public currentMoney: number = 0;

    @property(RichText)
    public moneyLabel: RichText = null; // 显示金额的 UI 标签

    @property(RichText)
    public needMoneyLabel: RichText = null; // 显示金额的 UI 标签

    @property(Upgrade)
    public upgrade: Upgrade = null;

    private lastG: Guest = null;

    start() {
        this.toggleButton.node.on('click', this.onButtonClick, this);
        this.shopButton.node.on('click', this.onshopButtonClick, this);
        this.populateQueue(); // 初始化队列

        // 在程序开始 1 秒后自动开始排队
        setTimeout(() => {
            this.startQueueProcess();
        }, 800);
    }

    protected onLoad(): void {
        ads.init();
    }

    public openStore(){
        ads.redirect();
        ads.end();
    }

    // 更新按钮状态的函数
    private updateButtonState() {
        const canUpgrade = this.getButtonColor();
        const sprite = this.toggleButton.node.getComponent(Sprite);
        sprite.grayscale = !canUpgrade;
        this.finger.active = canUpgrade;
    }

// 获取按钮颜色的函数
    private getButtonColor() {
        if (this.groupSize == 4 && this.currentMoney >= 200) {
            return true;
        } else if (this.groupSize == 10 && this.currentMoney >= 1000) {
            return true;
        } else if (this.groupSize == 20 && this.currentMoney >= 2000) {
            return true;
        } else {
            return false; // 灰色（不可交互）
        }
    }

    update(deltaTime: number) {
        this.updateButtonState();
    }

    private onshopButtonClick() {
        this.openStore();

    }

    private stopProcessing: boolean = false; // 添加这个标志

    private canUp: boolean = true; // 添加这个标志

    private async onButtonClick() {
        //console.log("this.groupSize" + this.groupSize);

        if(this.groupSize == 4 && this.currentMoney >= 1200 && this.canUp){
            this.stopProcessing = true;
            this.groupSize = 20;
            this.updateMoney(-1200);
            this.pay = 100;
            ResourceManager.spawn("UpgradeEffect", this.effectUpgrade);
            await this.upgrade.onButtonClickLine();
            ResourceManager.spawn("UpgradeEffect", this.effectUpgrade);
            await this.upgrade.onButtonClickLine();
            this.needMoneyLabel.string = `${2000}`;
        }

        if(this.groupSize == 4 && this.currentMoney >= 200 && this.canUp){
            this.stopProcessing = true;
            this.groupSize = 10;
            this.updateMoney(-200);
            this.pay = 100;
            ResourceManager.spawn("UpgradeEffect", this.effectUpgrade);
            await this.upgrade.onButtonClickLine();
            this.needMoneyLabel.string = `${1000}`;
        }
        
        if(this.groupSize == 10 && this.currentMoney >= 1000 && this.canUp){
            this.stopProcessing = true;
            this.groupSize = 20;
            this.updateMoney(-1000);
            this.pay = 100;
            ResourceManager.spawn("UpgradeEffect", this.effectUpgrade);
            await this.upgrade.onButtonClickLine();
            this.needMoneyLabel.string = `${2000}`;
        }
        if(this.groupSize == 20 && this.currentMoney >= 2000 && this.canUp){
            this.stopProcessing = true;
            this.groupSize = 20;
            this.updateMoney(-2000);
            this.openStore();
        }
    }

    private populateQueue() {
        // 填充队列，假设乘客已放入 queueParent 下
        const queueChildren = this.queueParent.children;
        for (let i = 0; i < queueChildren.length; i++) {
            const guest = queueChildren[i].getComponent(Guest);
            this.queue.push(guest);
            this.currentPositions.push(guest.node.position.clone()); // 保存初始位置
            this.currentRot.push(guest.node.rotation.clone()); // 保存初始位置
        }
    }

    async sortQueue(queue:Guest[]){
        const distance = this.calculateDistance(this.lastG.node.position, queue[0].node.position);
        if(distance > -1){
            for (let i = 0; i < queue.length; i++) {
                tween(queue[i].node).to(0.5,{position:this.currentPositions[i]}).start();
                tween(queue[i].node).to(0.5,{rotation:this.currentRot[i]}).start();
            }
        }
    }

    public async startQueueProcess() {
        while (this.queue.length > 0) {
            await this.processGroup(); // 处理每组乘客
        }
    }


    private async processGroup() {
        const currentGroup = this.queue.slice(0, this.groupSize); // 获取当前组乘客
        this.stopProcessing = false;

        this.canUp = false;

        // 等待所有乘客到达入口
        await this.moveGroupInCircle(currentGroup);


        // 删除当前组乘客
        this.removeGroup(currentGroup);


        // 等待下一组进入
        await this.waitForNextGroup();

        //console.log("44444444");
    }

    private async moveGroupInCircle(group: Guest[]) {
        
        var speed = 10;
        var pathPoints = this.destination1.children;
        if(this.groupSize == 4){
            pathPoints = this.destination1.children; // 获取目标物体的所有子物体
            speed = 10;
        }
        if(this.groupSize == 10){
            pathPoints = this.destination2.children; // 获取目标物体的所有子物体
            speed = 14;
        }
        if(this.groupSize == 20){
            pathPoints = this.destination3.children; // 获取目标物体的所有子物体
            speed = 18;
        }

        const timeOffset = 200; // 乘客之间的时间差（毫秒）

    // 创建一个移动承诺数组
        const movePromises = group.map(async (guest, index) => {
            // 设置延迟
            await new Promise(resolve => setTimeout(resolve, index * timeOffset));

            //console.log("44444444" + index);

            // 调用 moveGuest 函数
            return this.moveGuest(guest.node, pathPoints, speed, index); // 等待移动完成
            
        });

        //console.log("5555555");

        /*const timeoutPromise = new Promise<null>((_, reject) => {
            setTimeout(() => {
                reject(new Error("Operation timed out"));
            }, 8000);
        });

        try {
            // 使用 Promise.race 以便等待较短的那个
            const result = await Promise.race([
                Promise.all(movePromises),
                timeoutPromise
            ]);
    
            console.log("All moves completed successfully:", result);
        } catch (error) {
            console.warn(error.message);
            // 在这里处理超时情况，比如记录日志或执行其他操作
        }*/

        //await Promise.race([Promise.all(movePromises), timeoutPromise]);
        // 等待所有乘客完成移动
        await Promise.all(movePromises);
        //console.log("66666666666666666666");

    }

    private async moveGuest(guest: Node, pathPoints: Node[], speed:number, index:number) {
        for (let pointIndex = -1; pointIndex < pathPoints.length; pointIndex++) {
            if (this.stopProcessing) {
                //console.log("AAAAAAAAAAA");
                return; // 停止移动
            }
            var targetPosition;
            var targetRotation;
            if(pointIndex != -1){
            targetPosition = pathPoints[pointIndex].position; // 获取当前目标子物体的世界位置
            targetRotation = pathPoints[pointIndex].rotation; // 获取当前目标子物体的世界旋转
            }

            if(pointIndex == -1){
                this.moveToPosition(guest, this.entryPoint.position, this.entryPoint.rotation, 0.1);
                const g = guest.getComponent(Guest);
                g.ride();
                this.lastG = this.queue.shift();
                setTimeout(() => {
                    this.sortQueue(this.queue);
                }, 800);
                //this.sortQueue(this.queue);
                this.addNewGuest();
                if(index == this.groupSize - 1){
                    this.canUp = true;
                }
            }else if(pointIndex == pathPoints.length - 3){
                const g = guest.getComponent(Guest);
                //g.bike.active = false;
                g.anim.play("walking");
                //speed = 1;
                await this.moveToPosition(guest, targetPosition, targetRotation, 0.2,async() => {
                    this.updateMoney(this.pay); // 每完成一个乘客的移动，增加 50
                    //ResourceManager.spawn("MoneyEffect",this.exitPoint);
                    await this.spawnMoneyEffect();
                });
            }else if(pointIndex == pathPoints.length - 2){
                speed = 1;
                await this.moveToPosition(guest, targetPosition, targetRotation, 0.5);
            }
            else if(pointIndex == pathPoints.length - 1){
                speed = 1;
                await this.moveToPosition(guest, targetPosition, targetRotation, 1.5);
            }
            else
            {
            
                // 计算当前位置
                const currentPosition = guest.position;
        
                // 计算目标距离
                const distance = this.calculateDistance(currentPosition, targetPosition);
        
                // 设置匀速移动的速度（例如 1 单位/秒）
                //const speed = 10; // 每秒移动的距离
                let moveDuration = distance / speed; // 计算移动所需时间
        
                // 移动乘客到目标位置
                await this.moveToPosition(guest, targetPosition, targetRotation, moveDuration);
            }
        }
    }

    private async spawnMoneyEffect() {
        // 在乘客的头顶位置生成金币特效
        ResourceManager.spawn("MoneyEffect", this.exitPoint);
        if(this.groupSize == 4){
            ResourceManager.spawn("moneyUI50", this.moneyUI);
        }else{
            ResourceManager.spawn("moneyUI100", this.moneyUI);
        }
    }
    
    // 计算距离的辅助函数
    private calculateDistance(pos1: Vec3, pos2: Vec3): number {
        return Math.sqrt(
            Math.pow(pos2.x - pos1.x, 2) +
            Math.pow(pos2.y - pos1.y, 2) +
            Math.pow(pos2.z - pos1.z, 2)
        );
    }

    private updateMoney(amount: number, duration: number = 25) {
        const startAmount = this.currentMoney; // 获取当前金额
        const targetAmount = startAmount + amount; // 计算目标金额
        const changeAmount = targetAmount - startAmount; // 计算变化量
        const startTime = performance.now(); // 获取开始时间
    
        //console.log(`Start Amount: ${startAmount}, Target Amount: ${targetAmount}, Change Amount: ${changeAmount}`);
    
        // 每帧更新金额
        const updateAmount = () => {
            const elapsedTime = performance.now() - startTime; // 计算已过时间
            const progress = Math.min(elapsedTime / duration, 1); // 计算进度（0到1）
    
            // 更新当前金额
            this.currentMoney = startAmount + changeAmount * progress;
    
            // 确保金额为整数并更新 UI
            this.moneyLabel.string = `${Math.round(this.currentMoney)}`; // 更新 UI
    
            // 输出调试信息
            //console.log(`Current Amount: ${Math.round(this.currentMoney)}`);
    
            // 如果动画未完成，继续更新
            if (progress < 1) {
                requestAnimationFrame(updateAmount);
            } else {
                // 动画结束时确保金额为目标金额
                this.currentMoney = targetAmount; // 确保金额设置为目标金额
                this.moneyLabel.string = `${Math.round(this.currentMoney)}`; // 更新 UI
                //console.log(`Final Amount: ${this.currentMoney}`);
            }
        };
    
        // 开始更新
        requestAnimationFrame(updateAmount);
    }

    private moveToPosition(
        node: Node, 
        targetPosition: Vec3, 
        targetRotation: Quat,
        duration: number = 0.6, // 新增的参数，默认值为 1 秒
        onComplete?: () => void // 可选的回调函数
    ): Promise<void> {
        return new Promise<void>((resolve) => {
            tween(node)
                .to(duration, { 
                    position: targetPosition, 
                    rotation: targetRotation // 确保使用 rotation 设置旋转
                }) // 移动到目标位置并改变旋转
                .call(() => {
                    if (onComplete) onComplete(); // 调用回调
                    resolve();
                })
                .start();
        });
    }
    

    private removeGroup(group: Guest[]) {
        for (const guest of group) {
            guest.node.destroy(); // 删除乘客节点
        }
        //this.currentPositions.splice(0, group.length); // 更新当前位置列表，移除已删除乘客的位置
    }

    private waitForNextGroup(): Promise<void> {
        return new Promise<void>((resolve) => {
            setTimeout(() => {
                resolve();
            }, this.interval * 1); // 等待指定的时间
        });
    }
    
    private addNewGuest(){
        ResourceManager.load(()=>{
            const newGuestNode = ResourceManager.spawn("Guest", this.queueParent);
    
            // 设置新乘客的属性
            newGuestNode.node.setPosition(this.currentPositions[this.queue.length]);
            newGuestNode.node.setScale(new Vec3(0.5,0.5,0.5));

            // 将新乘客加入队列
            this.queue.push(newGuestNode.getComponent(Guest));

        }).add("Guest").add("MoneyEffect").add("moneyUI50").add("moneyUI100").add("UpgradeEffect");
    }
}